import { useFetch } from '@/pages/OrderModule/common/hooks/useFetch';
import { useEffect } from 'react';
import { deleteFieldConfig, getFieldConfig, updateFieldConfig } from './services';

export function useConfig({ code, initData, formatGetData }) {
  const {
    fetch: fetchFieldGetConfig,
    loading: getConfigLoading,
    data,
    updateData: setData,
  } = useFetch(
    (...params) => {
      const res = getFieldConfig(...params);
      const resolveRes = res.then((dataResp) => {
        if (dataResp?.data) {
          const resp = JSON.parse(dataResp.data.param || '[]');
          return resp;
        }
        return [];
      });
      return formatGetData ? formatGetData(resolveRes) : resolveRes;
      // return res.then((dataResp) => {
      //   if (formatGetData) {
      //     return formatGetData(dataResp?.data)
      //   } else {
      //     if (dataResp?.data) {
      //       const resp = JSON.parse(dataResp?.data.param || '[]');
      //       return resp;
      //     }
      //     return [];
      //   }
      // });
    },
    {},
    false,
    initData
  );

  const { fetch: fetchFieldSetConfig, loading: setConfigLoading } = useFetch(updateFieldConfig, {}, false);
  const editIndexSaveParams = { code: code, id: 0, param: '', userId: 0, uuid: 0 };

  const { fetch: fetchFieldDelConfig, loading: delConfigLoading } = useFetch(deleteFieldConfig, {}, false);


  useEffect(() => {
    fetchFieldGetConfig({
      ...editIndexSaveParams,
    });
  }, [delConfigLoading]);

  return {
    data,
    setData,
    getConfigLoading,
    setConfigLoading,

    save: (v, extraParams = {}) => {
      fetchFieldSetConfig({
        ...editIndexSaveParams,
        param: JSON.stringify(v),
        ...extraParams,
      });
    },
    del: (id) => {
      fetchFieldDelConfig({
        id
      })
    }
  };
}
